<template>
  <div class="divBox">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <div class="handle-box">
          <!--          <div class="input-box">-->
          <!--            <el-input-->
          <!--              v-model="searchForm.name"-->
          <!--              placeholder="请输入种子名称"-->
          <!--              class="input-with-select mr20"-->
          <!--              @keyup.enter.native="getList"-->
          <!--            >-->
          <!--              <el-button slot="append" icon="el-icon-search" @click="getList"></el-button>-->
          <!--            </el-input>-->
          <!--            <el-input-->
          <!--              v-model="searchForm.company"-->
          <!--              placeholder="请输入公司名称"-->
          <!--              class="input-with-select mr20"-->
          <!--              @keyup.enter.native="getList"-->
          <!--            >-->
          <!--              <el-button slot="append" icon="el-icon-search" @click="getList"></el-button>-->
          <!--            </el-input>-->
          <!--          </div>-->
          <el-button type="primary" @click="handleAdd">生成二维码</el-button>
        </div>
      </div>
      <el-table v-loading="listLoading" :data="tableData.data" style="width: 100%" size="small" class="mt25">
        <el-table-column prop="id" label="ID" min-width="60" />
        <!--        <el-table-column-->
        <!--          prop="seed_id"-->
        <!--          label="种子ID"-->
        <!--          min-width="80"-->
        <!--        />-->
        <el-table-column prop="name" label="种子名称" min-width="120" />
        <el-table-column prop="company" label="公司名称" min-width="150" />

        <el-table-column prop="number" label="生成数量" min-width="100" />
        <el-table-column prop="is_piece" label="是否按件打包" min-width="80">
          <template slot-scope="scope">
            <el-tag :type="scope.row.is_piece === 1 ? 'success' : 'info'">
              {{ scope.row.is_piece === 1 ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="progress" label="进度" min-width="100">
          <template slot-scope="scope">
            <el-progress :percentage="scope.row.progress"></el-progress>
          </template>
        </el-table-column>
        <el-table-column prop="add_time" label="添加时间" min-width="150" />
        <el-table-column label="操作" min-width="150" fixed="right">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="small"
              @click="handleDownload(scope.row)"
              :disabled="scope.row.progress < 100"
            >
              下载
            </el-button>
            <!--            <el-button-->
            <!--              type="danger"-->
            <!--              size="small"-->
            <!--              @click="handleDelete(scope.row)"-->
            <!--            >-->
            <!--              删除-->
            <!--            </el-button>-->
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          :page-sizes="[10, 20, 30, 40]"
          :page-size="searchForm.limit"
          :current-page="searchForm.page"
          layout="total, sizes, prev, pager, next, jumper"
          :total="tableData.total"
          @size-change="handleSizeChange"
          @current-change="pageChange"
        />
      </div>
    </el-card>

    <!-- 生成二维码弹窗 -->
    <el-dialog title="生成二维码" :visible.sync="dialogVisible" width="500px" :before-close="handleClose">
      <el-form ref="qrcodeForm" :model="qrcodeForm" :rules="rules" label-width="120px" class="qrcodeForm">
        <el-form-item label="种子" prop="id">
          <el-select
            v-model="qrcodeForm.id"
            filterable
            remote
            reserve-keyword
            placeholder="请选择或搜索种子"
            :remote-method="searchSeed"
            :loading="seedSearchLoading"
            style="width: 100%"
            @change="handleSeedChange"
            @focus="handleSeedFocus"
          >
            <el-option v-for="item in seedList" :key="item.id" :label="`${item.name}`" :value="item.id">
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px"
                >{{ item.company || '' }} - ID: {{ item.id }}</span
              >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="公司名称" prop="name">
          <el-input v-model="qrcodeForm.name" placeholder="请输入公司名称" />
        </el-form-item>
        <el-form-item :label="qrcodeForm.is_piece === 1 ? '每件袋数' : '生成数量'" prop="number">
          <el-input
            v-model.number="qrcodeForm.number"
            :placeholder="qrcodeForm.is_piece === 1 ? '请输入每件袋数(最大输入1000)' : '请输入生成数量(最大输入50000)'"
            style="width: 100%"
            @input="validateNumberInput"
          >
            <!--            <template slot="append">-->
            <!--              <el-button-group>-->
            <!--                <el-button icon="el-icon-minus" @click="decreaseNumber"></el-button>-->
            <!--                <el-button icon="el-icon-plus" @click="increaseNumber"></el-button>-->
            <!--              </el-button-group>-->
            <!--            </template>-->
          </el-input>
        </el-form-item>

        <el-form-item label="是否按件打包" prop="is_piece">
          <el-switch
            v-model="qrcodeForm.is_piece"
            :active-value="1"
            :inactive-value="0"
            active-text="是"
            inactive-text="否"
            @change="handlePackingModeChange"
          >
          </el-switch>
        </el-form-item>
        <el-form-item label="件数" prop="pieceNum" v-if="qrcodeForm.is_piece === 1">
          <el-input
            v-model.number="qrcodeForm.pieceNum"
            placeholder="请输入件数"
            style="width: 100%"
            @input="validatePieceNumInput"
          >
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitQrcode">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getQrcodeList, addQrcode, getCodeFile, deleteQrcode } from '@/api/qrcode';
import { getSeedList } from '@/api/seed';
import { mapState } from 'vuex';
import { AudioUtils } from '@/utils/audioUtils';

export default {
  name: 'QrcodeIndex',
  data() {
    return {
      searchForm: {
        page: 1,
        limit: 10,
        name: '',
        company: '',
      },
      listLoading: false,
      tableData: {
        data: [],
        total: 0,
      },
      dialogVisible: false,

      qrcodeForm: {
        id: '',
        name: '',
        number: null,
        is_piece: 0,
        pieceNum: 1,
      },
      seedList: [], // 种子列表
      seedSearchLoading: false, // 种子搜索加载状态
      searchTimer: null, // 搜索防抖定时器
      downloadUrls: null,
      currentQrcodeId: null,
      rules: {
        id: [{ required: true, message: '请选择种子', trigger: 'change' }],
        name: [{ required: true, message: '请输入公司名称', trigger: 'blur' }],
        number: [
          { required: true, message: '请输入生成数量', trigger: 'blur' },
          { 
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error('请输入生成数量'));
              } else if (value < 1) {
                callback(new Error('生成数量不能小于1'));
              } else {
                const max = this.qrcodeForm.is_piece === 1 ? 1000 : 50000;
                if (value > max) {
                  callback(new Error(`生成数量不能超过${max}`));
                } else {
                  callback();
                }
              }
            }, 
            trigger: 'blur' 
          }
        ],
        pieceNum: [{ required: true, message: '请输入件数', trigger: 'blur' }],
      },
    };
  },
  computed: {
    ...mapState('app', ['pageLimit']),
  },
  mounted() {
    this.getList();
    this.getSeedList().then(() => {
      // 在种子列表加载完成后，尝试加载上次选择的种子
      this.loadLastSelectedSeed();
    });
  },
  beforeDestroy() {
    // 清除搜索防抖定时器
    if (this.searchTimer) {
      clearTimeout(this.searchTimer);
    }
  },
  methods: {
    // 获取列表
    getList() {
      this.listLoading = true;
      getQrcodeList(this.searchForm)
        .then((res) => {
          if (res.status === 200) {
            this.tableData.data = res.data.list || [];
            this.tableData.total = res.data.count || 0;
          } else {
            this.$message.error(res.msg || '获取数据失败');
          }
        })
        .catch((err) => {
          this.$message.error(err.msg || '获取数据失败');
        })
        .finally(() => {
          this.listLoading = false;
        });
    },

    // 获取种子列表
    getSeedList(searchKeyword = '') {
      const params = {
        page: 1,
        limit: 200, // 获取较多数据以便选择
      };

      // 如果有搜索关键词，添加到参数中
      if (searchKeyword) {
        params.name = searchKeyword;
      }

      return new Promise((resolve) => {
        getSeedList(params)
          .then((res) => {
            if (res.status === 200) {
              this.seedList = res.data.list || [];
              resolve(this.seedList);
            } else {
              this.$message.error(res.msg || '获取种子列表失败');
              resolve([]);
            }
          })
          .catch((err) => {
            this.$message.error(err.msg || '获取种子列表失败');
            resolve([]);
          });
      });
    },

    // 搜索种子
    searchSeed(query) {
      if (query !== '') {
        this.seedSearchLoading = true;
        // 防抖处理
        clearTimeout(this.searchTimer);
        this.searchTimer = setTimeout(() => {
          this.getSeedList(query);
          this.seedSearchLoading = false;
        }, 300);
      } else {
        this.seedList = [];
      }
    },

    // 种子选择框获取焦点时
    handleSeedFocus() {
      // 如果没有数据，加载默认数据
      if (this.seedList.length === 0) {
        this.getSeedList();
      }
    },

    // 种子变更处理
    handleSeedChange(seedId) {
      // 根据选择的种子ID找到对应的种子数据
      const selectedSeed = this.seedList.find((item) => item.id === seedId);
      if (selectedSeed) {
        // 如果用户还没有手动输入公司名称，则自动填充
        if (!this.qrcodeForm.name) {
          this.qrcodeForm.name = selectedSeed.company || '';
        }
        
        // 保存选择的种子到本地存储
        this.saveSelectedSeed(selectedSeed);
      }
    },
    
    // 保存选择的种子到本地存储
    saveSelectedSeed(seed) {
      try {
        // 保存完整的种子对象
        localStorage.setItem('lastSelectedQrcodeSeed', JSON.stringify({
          id: seed.id,
          name: seed.name,
          company: seed.company
        }));
      } catch (error) {
        console.warn('保存选择的种子失败:', error);
      }
    },
    
    // 加载上次选择的种子
    loadLastSelectedSeed() {
      try {
        const lastSelectedSeedStr = localStorage.getItem('lastSelectedQrcodeSeed');
        if (lastSelectedSeedStr && this.seedList.length > 0) {
          const lastSelectedSeed = JSON.parse(lastSelectedSeedStr);
          // 检查上次选择的种子是否还存在于种子列表中
          const seedExists = this.seedList.some(seed => seed.id == lastSelectedSeed.id);
          if (seedExists) {
            this.qrcodeForm.id = lastSelectedSeed.id;
            // 如果用户还没有手动输入公司名称，则自动填充
            if (!this.qrcodeForm.name) {
              this.qrcodeForm.name = lastSelectedSeed.company || '';
            }
          }
        }
      } catch (error) {
        console.warn('加载上次选择的种子失败:', error);
      }
    },

    // 处理打包模式切换
    handlePackingModeChange(value) {
      // 保存当前选择的种子ID，避免模式切换后丢失
      const currentSeedId = this.qrcodeForm.id;
      const currentName = this.qrcodeForm.name;
      
      // 当切换到按件打包模式时
      if (value === 1) {
        // 如果当前生成数量超过按件打包的最大值，重置为null
        if (this.qrcodeForm.number && this.qrcodeForm.number > 1000) {
          this.qrcodeForm.number = null;
          this.$message.warning('已切换到按件打包模式，每件袋数最大为1000，请重新输入');
        }
        // 确保件数有默认值
        if (!this.qrcodeForm.pieceNum || this.qrcodeForm.pieceNum < 1) {
          this.qrcodeForm.pieceNum = 1;
        }
      } else {
        // 当切换到普通模式时
        if (this.qrcodeForm.number && this.qrcodeForm.number > 50000) {
          this.qrcodeForm.number = null;
          this.$message.warning('已切换到普通模式，生成数量最大为50000，请重新输入');
        }
        // 重置件数为默认值
        this.qrcodeForm.pieceNum = 1;
      }
      
      // 恢复之前选择的种子ID和名称
      this.qrcodeForm.id = currentSeedId;
      this.qrcodeForm.name = currentName;
      
      // 清除表单验证错误
      this.$nextTick(() => {
        if (this.$refs.qrcodeForm) {
          this.$refs.qrcodeForm.clearValidate(['number', 'pieceNum']);
        }
      });
    },

    // 切换分页
    pageChange(page) {
      this.searchForm.page = page;
      this.getList();
    },

    // 切换每页显示条数
    handleSizeChange(val) {
      this.searchForm.limit = val;
      this.getList();
    },

    // 添加二维码
    handleAdd() {
      // 初始化表单
      this.qrcodeForm = {
        id: '',
        name: this.$store.state.userInfo.userInfo?.company || '',
        number: null,
        is_piece: 0,
        pieceNum: 1,
      };
      
      // 尝试加载上次选择的种子
      this.loadLastSelectedSeed();
      
      this.dialogVisible = true;
    },

    // 下载二维码文件
    handleDownload(row) {
      if (row.progress < 100) {
        this.$message.warning('二维码正在生成中，请稍后再试');
        this.playErrorSound();
        return;
      }

      getCodeFile(row.id)
        .then((res) => {
          if (res.status === 200) {
            // 直接下载zip文件
            if (res.data.file) {
              this.downloadFile(res.data.file);
              // 播放成功提示音和语音
              this.playSuccessSound();
              setTimeout(() => {
                this.playVoice('下载已开始');
              }, 400);
            } else {
              this.$message.error('下载文件不存在');
              this.playErrorSound();
            }
          } else {
            this.$message.error(res.msg || '获取下载地址失败');
            this.playErrorSound();
          }
        })
        .catch((err) => {
          this.$message.error(err.msg || '获取下载地址失败');
          this.playErrorSound();
        });
    },

    // 下载文件
    downloadFile(url) {
      if (!url) {
        this.$message.error('下载地址不存在');
        return;
      }

      // 创建一个隐藏的a标签来下载文件
      const link = document.createElement('a');
      link.href = url;
      link.target = '_blank';
      link.style.display = 'none';

      // 从URL中提取文件名
      const filename = url.substring(url.lastIndexOf('/') + 1);
      link.download = filename;

      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },

    // 播放成功提示音
    playSuccessSound() {
      try {
        AudioUtils.generateDingSound();
      } catch (error) {
        console.warn('播放成功提示音失败:', error);
      }
    },

    // 播放错误提示音
    playErrorSound() {
      try {
        AudioUtils.generateErrorSound();
      } catch (error) {
        console.warn('播放错误提示音失败:', error);
      }
    },

    // 语音播报
    playVoice(text) {
      try {
        if ('speechSynthesis' in window) {
          // 停止当前播报
          speechSynthesis.cancel();

          const utterance = new SpeechSynthesisUtterance(text);
          utterance.lang = 'zh-CN';
          utterance.rate = 1.0;
          utterance.pitch = 1.0;
          utterance.volume = 1.0; // 最大音量

          speechSynthesis.speak(utterance);
        }
      } catch (error) {
        console.warn('语音播报失败:', error);
      }
    },

    // 提交二维码表单
    submitQrcode() {
      this.$refs.qrcodeForm.validate((valid) => {
        if (valid) {
          addQrcode(this.qrcodeForm)
            .then((res) => {
              if (res.status === 200) {
                this.$message.success('二维码生成任务已提交');
                // 播放成功提示音和语音
                this.playSuccessSound();
                setTimeout(() => {
                  this.playVoice('二维码生成任务已提交');
                }, 400);
                this.dialogVisible = false;
                this.getList();
              } else {
                this.$message.error(res.msg || '生成二维码失败');
                // 播放错误提示音
                this.playErrorSound();
              }
            })
            .catch((err) => {
              this.$message.error(err.msg || '生成二维码失败');
              // 播放错误提示音
              this.playErrorSound();
            });
        }
      });
    },

    // 删除二维码
    handleDelete(row) {
      this.$confirm('确定要删除该二维码记录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          deleteQrcode(row.id)
            .then((res) => {
              if (res.status === 200) {
                this.$message.success('删除成功');
                this.getList();
              } else {
                this.$message.error(res.msg || '删除失败');
              }
            })
            .catch((err) => {
              this.$message.error(err.msg || '删除失败');
            });
        })
        .catch(() => {
          this.$message.info('已取消操作');
        });
    },

    // 关闭弹窗
    handleClose() {
      this.$refs.qrcodeForm.resetFields();
      this.dialogVisible = false;
    },

    // 验证数量输入（使用el-input）
    validateNumberInput(val) {
      // 如果输入为空，保持为空
      if (val === '' || val === null || val === undefined) {
        this.qrcodeForm.number = null;
        return;
      }

      // 移除非数字字符
      val = val.toString().replace(/[^\d]/g, '');

      // 如果处理后为空，设为null
      if (val === '') {
        this.qrcodeForm.number = null;
        return;
      }

      // 转为数字并验证范围
      let num = Number(val);
      const max = this.qrcodeForm.is_piece === 1 ? 1000 : 50000;

      if (num > max) {
        num = max;
        this.$message.warning(`最大输入数量不能超过${max}`);
      } else if (num < 1) {
        num = 1;
        this.$message.warning('最小输入数量不能小于1');
      }

      // 更新值
      this.qrcodeForm.number = num;
    },

    // 验证件数输入（使用el-input）
    validatePieceNumInput(val) {
      // 移除非数字字符
      val = val.toString().replace(/[^\d]/g, '');

      // 转为数字并验证范围
      let num = val === '' ? 1 : Number(val);

      if (num < 1) {
        num = 1;
        this.$message.warning('最小件数不能小于1');
      }

      // 更新值
      this.qrcodeForm.pieceNum = num;
    },

    // 增加数量
    increaseNumber() {
      const max = this.qrcodeForm.is_piece === 1 ? 1000 : 50000;
      if (this.qrcodeForm.number < max) {
        this.qrcodeForm.number++;
      } else {
        this.$message.warning(`最大输入数量不能超过${max}`);
      }
    },

    // 减少数量
    decreaseNumber() {
      if (this.qrcodeForm.number > 1) {
        this.qrcodeForm.number--;
      } else {
        this.$message.warning('最小输入数量不能小于1');
      }
    },

    // 增加件数
    increasePieceNum() {
      this.qrcodeForm.pieceNum++;
    },

    // 减少件数
    decreasePieceNum() {
      if (this.qrcodeForm.pieceNum > 1) {
        this.qrcodeForm.pieceNum--;
      } else {
        this.$message.warning('最小件数不能小于1');
      }
    },
  },
};
</script>

<style scoped lang="scss">
.input-with-select {
  width: 300px;
}
.handle-box {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
}
.input-box {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  margin-bottom: 10px;
}
.mr20 {
  margin-right: 20px;
  margin-bottom: 10px;
}
.mt25 {
  margin-top: 25px;
}
.block {
  margin-top: 20px;
  text-align: right;
}

.download-links {
  padding: 20px;

  .download-item {
    display: flex;
    align-items: center;
    margin-bottom: 15px;

    .label {
      min-width: 100px;
      margin-right: 20px;
      font-weight: bold;
    }
  }
}
</style>
